package com.homework.third;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

/**
 * @Author WaveHi
 * @Date 24/8/2021 下午 7:32
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description 作业3
 */
public class ReadXML {

    public static void main(String[] args) {

        //获取xml文件
        File file = new File("day13/resources/person.xml");

        //获取Document构建器工厂
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        Document document = null;

        try {
            //获取Document构建器
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            //通过Document构建器解析配置文件获取Document对象
            document = documentBuilder.parse(file);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取根节点
        Element documentElement = document.getDocumentElement();

        //获取第一个linkman节点
        Node linkman = documentElement.getElementsByTagName("linkman").item(0);

        //通过linkman节点获取各个节点并相应的信息
        Element linkmantUp = (Element)linkman;
        System.out.println("name = " + linkmantUp.getElementsByTagName("name").item(0).getTextContent());


    }

}

//小结：解析xml文件的步骤
//     1.获取配置文件
//     2.获取Document构建器工厂
//     3.虎丘Document构建器
//     4.通过Document狗酱解析配置文件获取Document对象